package top.chendawei.aop;


import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.chendawei.aop.exceptions.CommonPartsExceptions;
import top.chendawei.util.CommonUtils;
import top.chendawei.util.params.ResultMessage;

/**
 * 异常处理
 */
@Slf4j
@RestControllerAdvice
public class WebExceptionHandler {
    @ExceptionHandler({CommonPartsExceptions.class})
    public ResultMessage exception(CommonPartsExceptions e) {
        log.error("发生业务异常:{}", e.getMessage());
        if (log.isTraceEnabled())
            log.trace("异常详情:{}", e.getMessage(), e);
        return ResultMessage.error(e.getCode(), CommonUtils.loadCauseMsg(e));
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultMessage bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "校验失败:";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ", ";
        }
        return ResultMessage.error(errorMesssage);
    }

}
